# zennotac-backend/app/services/ocr_service.py
import os
from pathlib import Path
from datetime import datetime
from app.config.base_setting import (
    backend_logger,
    UPLOAD_FOLDER,
    OCR_OUTPUT_FOLDER,
    ARCHIVE_UPLOAD_FOLDER,
    ARCHIVE_OCR_OUTPUT_FOLDER,
)
from app.utils.remote_ssh import (
    ssh_connect,
    upload_file,
    run_remote_script,
    download_file,
)
from app.utils.extract_text_from_pdf import extract_text_from_pdf
from app.services.progress_service import start_task, update_task, complete_task, fail_task, register_filename
import uuid

def generate_response_dict(source_filenames: list[str], ocred_paths: list[str], start_time: datetime) -> dict:
    """
    Build final JSON response with ocr_content, generated_files, and metadata.
    """
    ocr_content_map = extract_text_from_pdf(ocred_paths)
    generated_files = [Path(p).name for p in ocred_paths]
    now = datetime.now()

    return {
        "ocr_content": ocr_content_map,
        "generated_files": generated_files,
        "metadata": {
            "source_files": source_filenames,
            "generated_at": now.isoformat(),
            "processing_time": f"{(now - start_time).total_seconds():.2f}s",
        },
    }

def process_ocr_batch(abs_paths: list[str], output_dir: str) -> dict:
    """
    Local wrapper to OCR multiple files remotely and return structured JSON.
    """
    task_id = str(uuid.uuid4())
    start_task(task_id, total_steps=len(abs_paths), label="OCR in progress")
    
    client = ssh_connect()
    if not client:
        backend_logger.error("[OCR] SSH connection failed")
        raise ConnectionError("SSH connection failed")

    ocred_paths = []
    start_time = datetime.now()

    try:
        for idx, abs_path in enumerate(abs_paths, start=1):
            filename = os.path.basename(abs_path)
            base = Path(filename).stem

            register_filename(filename, task_id)
            upload_file(client, abs_path)

            backend_logger.info(f"Before run_remote_script - filename: {filename}")
            run_remote_script(client, filename, task_id)
            remote_filename = f"{base}_ocred.pdf"
            
            download_file(client, filename, remote_filename)

            ocred_path = os.path.join(output_dir, remote_filename)
            ocred_paths.append(ocred_path)

            update_task(task_id, idx, label=f"OCR {filename} ({idx}/{len(abs_paths)})")

        complete_task(task_id)
        backend_logger.info(f"[OCR] Batch completed: {task_id} for {len(abs_paths)} files")

        source_filenames = [os.path.basename(p) for p in abs_paths]
        return generate_response_dict(source_filenames, ocred_paths, start_time) | {
            "task_id": task_id,
            "filenames": source_filenames,  # <-- ADD THIS for multi-file response
        }

    except Exception as e:
        fail_task(task_id, str(e))
        backend_logger.exception(f"[OCR] Failed OCR batch processing: {e}")
        raise

    finally:
        client.close()


def handle_ocr_remote(abs_paths: list[str], output_dir: str) -> dict:
    """
    Alias to process_ocr_batch for now — maintains semantic separation if future local OCR added.
    """
    return process_ocr_batch(abs_paths, output_dir)
